package com.ndp.fb.walle.business.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.storage.StorageService;
import com.ndp.fb.enums.ErrorType;
import com.ndp.fb.rdb.api.EcFontRdbService;
import com.ndp.fb.rdb.model.EcFont;
import com.ndp.fb.rdb.model.Pager;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.util.FileUtil;
import com.ndp.fb.walle.business.EcFontSercie;
import com.ndp.fb.walle.util.FileUploadUtils;
import org.apache.commons.compress.compressors.FileNameUtil;
import org.apache.commons.io.FileUtils;
import org.apache.tools.ant.types.FileList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by infi.he on 2016/4/26.
 */
@Component
public class EcFontSercieImpl implements EcFontSercie {

    Logger logger = LoggerFactory.getLogger(EcFontSercieImpl.class);

    @Reference
    EcFontRdbService ecFontRdbService;

    @Autowired
    StorageService storageService;

    @Override
    public Pager<EcFont> findPager(Long orgId, Integer cpage, Integer psize) {
        Pager<EcFont> pager = ecFontRdbService.findPager(orgId, cpage, psize);
        return pager;
    }

    @Override
    public EcFont findByFontName(Long orgId, String fontName) {
        return ecFontRdbService.findByFontName(orgId, fontName);

    }

    @Override
    public List<EcFont> getByTemplateId(Long templateId) {
        return ecFontRdbService.getByTemplateId(templateId);
    }

    @Override
    public void uploadFont(List<MultipartFile> fileList, String contextPath, String fontName123, String fontWeight, User user) throws Exception {
        File fontFile;
        EcFont ecFont;
        String sep = System.getProperty("file.separator");
        for (MultipartFile multipartFile : fileList) {
            String name = multipartFile.getName();
            if ("fontFile".equalsIgnoreCase(name)) {
                File tempFontFile = FileUploadUtils.multipartFile2File(multipartFile, contextPath);
                fontFile = new File(tempFontFile.getParent(), multipartFile.getOriginalFilename());
                FileUtils.copyFile(tempFontFile, fontFile);

                Font font = Font.createFont(Font.TRUETYPE_FONT, fontFile);
                String fontName = font.getFamily();

                String extension = FileUtil.getExtension(fontFile.getName());
                String baseFileName =  FileUtil.getFileBaseName(fontFile.getName()).replaceAll("\\W","_");
                String fileName = baseFileName + "." + extension;

                //生成上传的文件s3地址
                String storePath = storageService.storeFontAsPublic(null, fontFile, fileName);

                StringBuffer fileLocalUrl = new StringBuffer();
                fileLocalUrl.append(contextPath).append("upload").append(sep).append(multipartFile.getOriginalFilename());

                //生成字体预览图
                String previewImghttpUrl = storageService.storeFontAsPublicResultHttp(null, buildPreviewImg(contextPath, fileLocalUrl.toString(), fontWeight), null);

                //两个临时文件删除
                fontFile.delete();
                tempFontFile.delete();

                ecFont = new EcFont();
                ecFont.setCreateTime(System.currentTimeMillis());
                ecFont.setFontName(fontName);
                ecFont.setStorePath(storePath);
                ecFont.setFontUrl(storageService.getHttpUrl(storePath));
                ecFont.setFontWeight(fontWeight);
                ecFont.setUserId(user.getTicket());
                ecFont.setOrgId(user.getOrgId());
                ecFont.setPreviewImg(previewImghttpUrl);
                ecFontRdbService.save(ecFont);
            }
        }

    }

    /**
     * 构建预览图
     * @param filePath
     * @return
     */
    public File buildPreviewImg(String filePath, String fileLocalUrl, String fontWeight) {
        String fileName = System.currentTimeMillis() + ".jpg";
        String path = filePath + "/" + fileName;
        File file = new File(path);

        BufferedImage bi = new BufferedImage(CommonConstants.FONT_PREVIEW_WIDTH, CommonConstants.FONT_PREVIEW_HEIGHT,
                BufferedImage.TYPE_INT_RGB);

        Graphics2D g2 = (Graphics2D) bi.getGraphics();
        g2.setBackground(Color.WHITE);
        g2.clearRect(0, 0, CommonConstants.FONT_PREVIEW_WIDTH, CommonConstants.FONT_PREVIEW_HEIGHT);
        //文本抗锯齿提示值——文本呈现需要使用字体资源中的信息，这些信息指定了每个点大小是否适合应用
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        //字体小数规格提示值——用子像素精确度定位字符字形。
        g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);

        g2.setFont(loadFont(fileLocalUrl, 24, fontWeight));
        g2.setPaint(Color.BLACK);

        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        g2.drawString(CommonConstants.FONT_PREVIEW_STR, 0, 30);
        g2.drawString("123456789", 0, 60);

        try {
            ImageIO.write(bi, "jpg", file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    public  Font loadFont(String fontFileName, float fontSize, String fontWeight)  //第一个参数是外部字体名，第二个是字体大小
    {
        try
        {
            File file = new File(fontFileName);
            FileInputStream aixing = new FileInputStream(file);
            Font dynamicFont = Font.createFont(Font.TRUETYPE_FONT, aixing);
            Font dynamicFontPt = dynamicFont.deriveFont(fontSize);
            Font dynamicFontBold;
            if("bold".equals(fontWeight))
                dynamicFontBold = dynamicFontPt.deriveFont(Font.BOLD);
            else
                dynamicFontBold = dynamicFontPt.deriveFont(Font.PLAIN);
            aixing.close();
            return dynamicFontBold;
        }
        catch(Exception e)
        {
            logger.error("加载字体异常：", e);
            return new java.awt.Font("宋体", Font.PLAIN, 24);
        }
    }

}